import os, sys, json, pika, time, redis, pymysql

# #############################################################################################
# 1. 配置mysql
# #############################################################################################
def sql():
    conn = pymysql.connect(host='user-db', user="root", passwd="123456", database="userdb")
    cursor = conn.cursor()
    
    return conn, cursor
    
conn, cursor = sql()
###############################################################################################


# #############################################################################################
# 2. 配置rabbitMQ
# #############################################################################################
username = 'user01'
pwd = '123456'
ip_addr = 'fanggx.xyz'
port_num = 3381

credentials = pika.PlainCredentials(username, pwd)

connection = pika.BlockingConnection(
    pika.ConnectionParameters(ip_addr, port_num, '/', credentials)    
)
channel = connection.channel()

channel.queue_declare(queue='TestDirectQueue', durable=True)
###############################################################################################

# 这里定义开始时间(从某一时间到现在的毫秒数)
start = time.time()*1000

def callback(ch, method, properties, body):
    global start
    conn_redis = redis.Redis(host='fanggx.xyz', port=3390)
    infoGetted = str(body, encoding='utf-8')
    info = infoGetted.split('_')
    
    # 检查用户是否is_suc=1
    sql_is_suc = "Select is_suc From userTable Where UserId = %d" % int(info[1])
    cursor.execute(sql_is_suc)
    is_suc = cursor.fetchone()
    try:  # 如果数据库中有数据
        is_suc = int(is_suc[0])

        if is_suc == 0:  # 如果没选
        
            # 检查库存是否还有（即>=0）
            sql_remain = "Select remainCount From goodTable Where GoodId = %d" % int(info[0])
            cursor.execute(sql_remain)
            remain_num = cursor.fetchone()
            remain_num = int(remain_num[0])

            if remain_num >= 1:  # 如果还有库存
                
                # - - - - - 1. 插入数据库 - - - - -
                # 插入orderTable
                sql_insert = "INSERT INTO orderTable(UserId, GoodId) VALUES (%d, %d)" % (int(info[1]), int(info[0]))
                cursor.execute(sql_insert)
                conn.commit()
                
                # 更新userTable
                sql_update = "UPDATE userTable SET is_suc = %d WHERE UserId = %d" % (1, int(info[1]))
                cursor.execute(sql_update)
                conn.commit()
                
                # 库存去1
                sql_dec = "UPDATE goodTable SET remainCount=remainCount-1 WHERE GoodId = %d" % int(info[0])
                cursor.execute(sql_dec)
                conn.commit()
                # - - - - - - - - - - - - - - - - -

                # - - - - - 2. 操作redis - - - - - -
                conn_redis.set(int(info[0]), conn_redis.get(int(info[0]))-1)
                conn_redis.set(str(info[1]), 1)
                # - - - - - - - - - - - - - - - - -
                
            elif remain_num <= 0:  # 如果没有库存了
                conn_redis.set(str(info[1]), 0)

        elif is_suc == 1:  # 如果选了
            conn_redis.set(str(info[1]), 1)

    except:  # 如果没查到
        pass
    
    # - - - - - 3. 检查队列长度与间隔时间写回redis - - - - - -
    rabbit_queue = channel.queue_declare(queue='TestDirectQueue', durable=True)
    queue_size = rabbit_queue.method.message_count
    if queue_size == 0:

        # 这里定义检查时间(从某一时间到现在的毫秒数)
        end = time.time()*1000
        used = end - start
        if used > 1000:
            
            key_list = [1, 2, 3, 4]
            for key in key_list:
                sql_selectTime = "Select remainCount From goodTable Where GoodId = %d" % int(key)
                cursor.execute(sql_selectTime)
                remainNum = cursor.fetchone()
                conn_redis.set(key, int(remainNum[0]))
            
            start = end
    
    ch.basic_ack(delivery_tag = method.delivery_tag)


# ##############################
# 3. 运行rabbitMQ
# ##############################
channel.basic_consume(queue='TestDirectQueue', on_message_callback=callback, auto_ack=False)

channel.start_consuming()